# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import pymongo
import pymysql
from .settings import *


# mongo
class BaiduMongoPipeline(object):

    def open_spider(self, spider):
        self.conn = pymongo.MongoClient(MONGO_HOST, MONGO_PORT)
        self.db = self.conn[MONGO_DB]
        self.myset = self.db[MONGO_SET]

    def process_item(self, item, spider):
        self.myset.insert_one(dict(item))
        return item


# mysql
class BaiduMysqlPipeline(object):

    def open_spider(self, spider):
        # 创建数据库连接
        self.db = pymysql.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PWD, MYSQL_DB, charset=CHARSET)
        # 创建游标对象
        self.cursor = self.db.cursor()

    def process_item(self, item, spider):
        ins = 'insert into 数据表名 values(%S,%S,%S)'
        li = [
            item[''].strip(),
        ]
        # 插入到数据库
        self.cursor.execute(ins, li)
        # 提交数据
        self.db.commit()

        return item

    def close_spider(self, spider):
        # 关闭游标和连接
        self.cursor.close()
        self.db.close()
